
package com.dkm.modules.wx.file.service.impl;

import com.dkm.modules.wx.file.mapper.FileMapper;
import com.dkm.modules.wx.file.model.FileModel;
import com.dkm.modules.wx.file.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassName FileServiceImpl
 * @Description: 文件操作实现类
 * @Author yangbin
 * @Date 2019-09-05 23:09
 * @Version V1.0
 **/
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private Environment env;
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private FileMapper fileMapper;

    @Override
    /**
     *@描述   文件上传
     *@参数  [file, fileModel]
     *@返回值  void
     *@创建人  yangbin
     *@创建时间  2019/10/16
     */
    public void uploadFile(MultipartFile file, FileModel fileModel) {

        try {
            //读取文件上传路径
            String filePath = env.getProperty("upload-file-path").toString();
            byte[] bytes = file.getBytes();

            Path path = Paths.get(filePath + fileModel.getBusiness() + "/" + fileModel.getFileName());
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(filePath + fileModel.getBusiness()));
            }

            //文件写入指定路径
            Files.write(path, bytes);
            //存库
            fileMapper.insert(fileModel);
            logger.debug("文件上传成功...");

        } catch (IOException e) {
            e.printStackTrace();
            ;
        }
    }

        @Override
        public FileModel getFileById(String imgId) {
                return fileMapper.selectById(imgId);
        }

        @Override
        public void insertFileInfo(FileModel fileModel) {
                fileMapper.insert(fileModel);
        }
    }